#include "GameManager.h"

// P U B L I C   F U N C T I O N S
// ===============================

CGameManager::CGameManager(CKernel *inKernel, long lPriority) : IKernelTask( "GameManager", 20 )
{
	kernel = inKernel;
	logger << "Child constructor done." << std::endl;
}  // END CGameManager.

CGameManager::~CGameManager()
{

}

bool CGameManager::Start()
{
	logger << "Starting task." << std::endl;

	updateTimer = GCPtr<IKernelTask>( UpdateTimer::getInstance() );
	input = GCPtr<IKernelTask>( Input::getInstance() );
	renderer2d = GCPtr<IKernelTask>( Renderer2d::getInstance() );
	netClient = GCPtr<IKernelTask>( NetClient::getInstance() );
	
	kernel->AddTask(updateTimer);
	kernel->AddTask(input);
	kernel->AddTask(renderer2d);
	kernel->AddTask(netClient);
	CResourceManager manager;
	player = new CUnit(manager.LoadImage("..//Graphics//test_image.bmp"));
	AnI = new CUnit(manager.LoadImage("..//Graphics//test_image.bmp"));
	AnI->xVel = 200;
	AnI->yPos = 300;
	AnI->xPos = 150;

	Renderer2d::getInstance()->addRenderable(player);
	Renderer2d::getInstance()->addRenderable(AnI);

	waitCounter = 0;
	
	return true;

}  // END Start.


void CGameManager::Stop()
{
	logger << INFO << "Stopping task." << std::endl;

}  // END Stop.


void CGameManager::Update()
{
	if (Input::getInstance()->isEscPressed() || input->CanKill())
	{
		kernel->RemoveAllTasks();
	}

	player->yVel = 0;
	if (Input::getInstance()->isUpPressed())
	{
		player->yVel -= player->moveSpeed;
	}
	if (Input::getInstance()->isDownPressed())
	{
		player->yVel += player->moveSpeed;
	}

	player->xVel = 0;
	if (Input::getInstance()->isRightPressed())
	{
		player->xVel += player->moveSpeed;
	}
	if (Input::getInstance()->isLeftPressed())
	{
		player->xVel -= player->moveSpeed;
	}

	player->xPos += player->xVel * (UpdateTimer::getInstance()->getTimeDelta() / 1000.f);
	player->yPos += player->yVel * (UpdateTimer::getInstance()->getTimeDelta() / 1000.f);
	AnI->xPos += AnI->xVel * (UpdateTimer::getInstance()->getTimeDelta() / 1000.f);

	// turn left
	if (AnI->xPos > 650)
	{
		AnI->xVel = -AnI->xVel;
	}

	// turn right
	if (AnI->xPos < 0)
	{
		AnI->xVel = -AnI->xVel;
	}
	
	++waitCounter;
	if (waitCounter > 100)
	{
		CoordPacket newPacket;
		newPacket.type = UPDATE_POSITION;
		newPacket.coords.xPos = player->xPos;
		newPacket.coords.yPos = player->yPos;

		NetClient::getInstance()->queuePacket( newPacket );
		waitCounter = 0;
	}
	
}  // END Update.